<!--
      仅使用upload+obs,不在插件内回显上传文件
-->
<template>
  <div>
    <el-upload
      action="#"
      :http-request="uploadQiniuCloud"
      ref="upload"
      :on-change="beforeUpload"
      :class="{hide:hideUploadEdit}"
      list-type="picture-card"
      :show-file-list="false"
      multiple
      drag
      :accept="acceptType"
      :auto-upload="true"
    >
      <i class="el-icon-upload"></i>
      <div style="position: absolute;top: 44px;width: 100%;">将文件拖到此处，或<em>点击上传</em></div>
      <div style="position: absolute;top: 165px;width: 100%;" class="el-upload__tip" slot="tip">最多可以上传10个文件，单个文件不可超过100M。</div>
    </el-upload>
  </div>
</template>
<script>

import * as qiniuTools from "../../util/qinnu_upload"

var obsClient;
export default {
  name: 'creativeUploadProdObs',
  props: {
    limit: {
      type: Number,
      default: 50,
    },
    fileMap: Array,
    plugInUnit: String,
    acceptType: {
      type: String,
      default: ".jpg,.jpeg,.gif,.png,.bmp,.mp4,.mov,.avi,.mp3,.ogg,.rmvb,.mkv,.xls,.xlsx"
    },
  },
  data() {
    return {
      dialogType: '',
      dialogImageUrl: '',//dialog内的文件
      dialogVisible: false,
      disabled: false,
      hideUploadEdit: false,
    }
  },
  methods: {
    callbackFunc(tmpUrl) {
      this.$emit("callbackFunc", tmpUrl)
    },
    reset() {
      this.hideUploadEdit = false
      this.fileMap = []
    },
    setUploadFileType(fileType){
      this.acceptType = fileType
    },
    beforeUpload(file, fileList) {
      if (this.limit && this.fileMap.length >= this.limit) {
        this.postMessage("上传的文件数量一次性不可超过" + this.limit + "个!", "warning");
        this.remove(file)
        return false;
      }
      // const extension = ["image", "video"].includes(this.creativeType(file));
      // if (!extension) {
      //   this.postMessage("上传的文件格式只能是.jpg,.jpeg,.gif,.png,.bmp,.mp4,.mov,.avi,.mp3,.ogg,.rmvb,.mkv!", "warning");
      //   this.remove(file);
      //   return false;
      // } else if (file.size > 100 * 1024 * 1024) {
      //   this.postMessage("上传的单个文件不能超过100M!", "warning");
      //   this.remove(file)
      //   return false;
      // } else {
      //   let totalSize = file.size;
      //   this.fileMap.forEach((f) => {
      //     totalSize += f.file.size;
      //   });
      //   if (totalSize > 500 * 1024 * 1024) {
      //     this.postMessage("上传的所有文件不能超过500M!", "warning");
      //     this.remove(file)
      //     return false;
      //   }
      // }
      let data = []
      if (Number(this.plugInUnit)) {
        data = []
        for (let i = 0; i < Number(this.plugInUnit); i++) {
          data.push([])
        }
      }
      this.fileMap.push({
        file: file,
        name: file.name,
        url: file.url,
        uid: file.uid,
        progress: 0,
        type: this.creativeType(file),
        data: data,
        thought: '',
      })
      this.hideUploadEdit = this.limit && (this.fileMap.length >= this.limit);
      return true;

    },

    uploadQiniuCloud(file) {
      let self = this
      let fileData = qiniuTools.getFileData(file)
      let callback = {
        next(res) {
          let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          if (fileIdx !== -1) {
            self.fileMap[fileIdx].progress =
              Math.trunc(res.total.percent)
          }
        },
        error(err) {
          this.$message({
            type: 'error',
            message: '图片上传失败！' + JSON.stringify(err)
          })
          let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          if(fileIdx !== -1) self.fileMap[fileIdx].url = '-1'
        },
        complete(res) {
          let fileIdx = self.fileMap.findIndex(item => item.uid === file.file.uid);
          if (fileIdx !== -1) {
            self.fileMap[fileIdx].url = 'http://' + fileData.server + '/' + res.key
            let tmpUrl = 'http://' + fileData.server + '/' + res.key
            self.callbackFunc(tmpUrl)
          }
        }
      }
      let uploader = qiniuTools.uploadQiniuCloud(file, fileData)
      uploader.subscribe(callback)
    },

    uploadCompleted() {
      let uploadingCount = 0;
      this.fileMap.forEach((file) => {
        if (file.progress != 100) {
          uploadingCount++;
        } else if (file.url.toLowerCase().startsWith('blob:')) {
          uploadingCount++;
        }
      });
      return (uploadingCount == 0);
    },
    postMessage(msg, type) {
      let self = this;
      if (self.errorMessage == msg) {
        return;
      }
      self.errorMessage = msg;
      self.$message({
        message: msg,
        type: type,
      });
    },
    removeByUid(uid) {
      let fileList = this.$refs.upload.uploadFiles;
      for (let i in fileList) {
        if (uid == fileList[i].uid) {
          fileList.splice(i, 1);
          break;
        }
      }
      this.fileMap.forEach((item, index) => {
        if (item.uid === uid) {
          this.fileMap.splice(index, 1)
        }
      })
      this.hideUploadEdit = this.limit && (this.fileMap.length >= this.limit);
    },
    remove(file) {
      this.removeByUid(file.uid);
    },
    //判断素材类型
    creativeType(file) {
      let type = '';
      let url = file.url;
      if (url != null) {
        url = url.split('?')[0];
      }
      let name = file.name;
      if (name != null) {
        name = name.split('?')[0];
      }

      let urlTail = ((url != null && url.indexOf('.') >= 0) ? (url.substring(url.lastIndexOf('.') + 1)) : '').toLowerCase();
      let nameTail = ((name != null && name.indexOf('.') >= 0) ? (name.substring(name.lastIndexOf('.') + 1)) : '').toLowerCase();

      let imgList = ['jpg', 'jpeg', 'png', 'gif', 'bmp']
      let videoList = ['mp4', 'mov', 'avi', 'mp3', 'ogg', 'rmvb', 'mkv']
      // let docxList = ['']
      if (imgList.includes(urlTail) || imgList.includes(nameTail)) {
        type = 'image'
      } else if (videoList.includes(urlTail) || videoList.includes(nameTail)) {
        type = 'video'
      }
      return type
    },
  }
}
</script>
<style lang="scss">
// 隐藏上传按钮
.hide .el-upload--picture-card {
  display: none;
}

// 添加/删除文件时去掉动画过渡
.el-upload-list__item {
  transition: none !important;
}

.el-upload-list--picture-card {
  display: block;
}

.upload-error {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center
}
</style>
